package com.viknix.threadpool.manager.client.enums;

import java.util.Arrays;
import java.util.Optional;

/**
 * @Author: Dongqi
 * @Date: 2021/10/27 11:15
 * @Version 1.0
 * @Description: 拒绝策略枚举
 */
public enum RejectedTypeEnum {

    /**
     * 被拒绝任务的程序由主线程执行
     * {@link java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy}
     */
    CALLER_RUNS_POLICY(1, "CallerRunsPolicy"),

    /**
     * 被拒绝任务的处理程序, 抛出异常
     * {@link java.util.concurrent.ThreadPoolExecutor.AbortPolicy}
     */
    ABORT_POLICY(2, "AbortPolicy"),

    /**
     * 被拒绝任务的处理程序, 默默地丢弃被拒绝的任务。
     * {@link java.util.concurrent.ThreadPoolExecutor.DiscardPolicy}
     */
    DISCARD_POLICY(3, "DiscardPolicy"),

    /**
     * 被拒绝任务的处理程序, 它丢弃最早的未处理请求, 然后重试
     * {@link java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy}
     */
    DISCARD_OLDEST_POLICY(4, "DiscardOldestPolicy");

    private Integer code;
    private String name;

    RejectedTypeEnum(int code, String name) {
        this.code = code;
        this.name = name;
    }

    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 根据 code 返回名称
     * @return name
     */
    public static String getNameByCode(int code) {
        Optional<RejectedTypeEnum> rejectedTypeEnum = Arrays.stream(RejectedTypeEnum.values())
                .filter(each -> each.code == code)
                .findFirst();
        return rejectedTypeEnum.map(each -> each.name).orElse("");
    }

    /**
     * 根据 code 返回枚举对象
     * @return name
     */
    public static RejectedTypeEnum getEnumByCode(int code) {
        Optional<RejectedTypeEnum> rejectedTypeEnum = Arrays.stream(RejectedTypeEnum.values())
                .filter(each -> each.code == code)
                .findFirst();
        return rejectedTypeEnum.get();
    }
}
